##  TO DO: 替换矩阵中的元素
##
##  Author: jeason zhao
################################################################

#' @name decode
#' @description 根据提供的替换对象，替换矩阵中的元素
#' @param x 需要替换元素的矩阵
#' @param search 需要替换的元素在矩阵中的原始值
#' @param replace 替换后的值
#' @param default 其余不发生替换的值对应的具体值
#' @returnType 
#' @return 
#' @examples
#'   b <- matrix(c(1,3,4,4,1, 2), ncol = 2)
#'   decode(b, search = c(1, 2,3, 4), replace = c("A", "B", "C", "D"))
#'   decode(b, search = c(1, 2,3, 4, 5), replace = c("A", "B", "C", "D", "E"))
#'   decode(b, search = c(1, 2,3, 5), replace = c("A", "B", "C", "E"))
#'   decode(b, search = c(1, 2,3, 5), replace = c("A", "B", "C", "E"), default = "X")
decode <- function(x, search, replace, default = NULL) {
  
  # build a nested ifelse function by recursion
  decode.fun <- function(search, replace, default = NULL)
    if (length(search) == 0L) {
      function(x) if (is.null(default)) x else rep(default, length(x))
    } else {
      function(x) ifelse(x == search[1L], replace[1L],
                         decode.fun(tail(search,  -1L),
                                    tail(replace, -1L),
                                    default)(x))
    }
  
  return(decode.fun(search, replace, default)(x))
}